<?php
use com\masfletes\db\DBUtil;

class OperationController_RoutesController extends JController {

    private $userSessionId;
    
     public function init() {
        parent::init();
        if (!Model3_Auth::isAuth()) {
            $this->redirect('Index/index');
        }
        $this->userSessionId = $_SESSION['USERSESSIONID'];
    }
    
    public function indexAction() {
        //Solo el Index se devuelve de manera normal(text/html)
        $this->setResponseJSON(FALSE);
        
        //Includes específicos de esta página        
        $this->view->customScripts .= $this->view->getJsManager()->loadJsFile('application/OperationController/Routes/routesApp.js', false, TRUE);
        $this->view->getJsManager()->addJsVarEncode('contextPath', $this->view->url(array(
                    'controller' => 'Routes')));
        $this->view->getJsManager()->addJsVarEncode('contextPathPoints', $this->view->url(array(
                    'controller' => 'Points')));
        $this->view->setTemplate('GeneralContentLayout');
    }
    
    public function getRoutesAction() {
        $params = $this->getRequest()->getPostJson();
        
        $page = $this->getArrayValue('page', $params);
        $limit = $this->getArrayValue('rowsPerPage', $params);
        $sidx = $this->getArrayValue('sortField', $params);
        $sord = $this->getArrayValue('sortDir', $params);
        $id = $this->getArrayValue('id', $params);
        
        if (!$sidx)
            $sidx = 1;

        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'listar');
            $conn = $this->getConnection();

            $parameters = array($this->userSessionId, $page, $limit, $sidx, $sord, $id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routes_listar', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (PDOException $ex) {
            $errMsg = $ex->getMessage(); //utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            }
            return;
        } catch (Exception $generalEx) {
            echo json_encode(array("error" => $generalEx->getMessage(), "code" => $generalEx->getCode(), "trace" => $generalEx->getTraceAsString()));
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function saveAction(){
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);        
        $code = $this->getArrayValue('code', $params);
        $name = $this->getArrayValue('name', $params);
        $status = $this->getArrayValue('status', $params);
        $capacity = $this->getArrayValue('capacity', $params);
        $factor = $this->getArrayValue('factor', $params);
        $close = $this->getArrayValue('close', $params) == null ? 0 : $this->getArrayValue('close', $params);
        $controllerId = Model3_Auth::getCredentials("id");
                    
        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', ($id==null) ? 'agregar' : 'editar');
            
            $conn = $this->getConnection();
            $parameters = array($id, $code, $name, $status, $capacity, $factor, $close, $controllerId);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routes_guardar', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function deleteAction() {
          $params = $this->getRequest()->getPostJson();
          $id = $params['id'];
          if($id==null)
                return;
          try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'eliminar');
            
            $conn = $this->getConnection();
            $parameters = array($id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routes_borrar', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = /*utf8_encode(*/$ex->getMessage()/*)*/;
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));
            }
            return;
        }
        echo json_encode($resultsets);
     }
     
     public function getRoutePointsAction(){
         //id, route_id, point_id, order_number, STATUS, arrival_time, required, nombre, tipo
        $params = $this->getRequest()->getPostJson();

        $page = $this->getArrayValue('page', $params);
        $limit = $this->getArrayValue('rowsPerPage', $params);
        $sidx = $this->getArrayValue('sortField', $params);
        $sord = $this->getArrayValue('sortDir', $params);
        $idRoute = $this->getArrayValue('route_id', $params);

        if (!$sidx)
            $sidx = 1;

        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'listar');
            $conn = $this->getConnection();

            $parameters = array($page, $limit, $sidx, $sord, $idRoute);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routePoint_list', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (PDOException $ex) {
            $errMsg = $ex->getMessage(); //utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            }
            return;
        } catch (Exception $generalEx) {
            echo json_encode(array("error" => $generalEx->getMessage(), "code" => $generalEx->getCode(), "trace" => $generalEx->getTraceAsString()));
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function routePointSaveAction() {
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);        
        $route_id = $this->getArrayValue('route_id', $params);
        $point_id = $this->getArrayValue('point_id', $params);
        $order_number = $this->getArrayValue('order_number', $params);
        $status = $this->getArrayValue('status', $params);
        $arrival_time = $this->getArrayValue('arrival_time', $params);
        $required = $this->getArrayValue('required', $params);
        
        if($point_id==null || $arrival_time==null){
            echo json_encode(array("error" => "El punto de venta y el tiempo de llegada no pueden estar en blanco."));
            return;
        }
        if($arrival_time<0||$arrival_time>59){
            echo json_encode(array("error" => "El tiempo de llegada debe estar entre 0 y 59 minutos"));
            return;
        }
             
        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', ($id==null) ? 'agregar' : 'editar');
            
            $conn = $this->getConnection();
            $parameters = array($id, $route_id, $point_id, $order_number, $status, $arrival_time, $required);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routePoint_save', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = $ex->getMessage();            
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function routePointDeleteAction() {
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);
        if ($id == null)
            return;
        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'eliminar');

            $conn = $this->getConnection();
            $parameters = array($id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routePoint_delete', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = $ex->getMessage();
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/* , "trace" => $ex->getTraceAsString() */));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function routePointChangeOrderAction(){
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);
        $dir = $this->getArrayValue('dir', $params);
        if ($id == null)
            return;
        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'agregar');
            $conn = $this->getConnection();
            $parameters = array($id, $dir);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routePoint_changeOrder', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = $ex->getMessage();
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/* , "trace" => $ex->getTraceAsString() */));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function routeToggleOpenCloseAction(){
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);
        $close = $this->getArrayValue('close', $params);
        if ($id == null)
            return;
        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'editar');
            $conn = $this->getConnection();
            $parameters = array($id, $close);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routes_toggleOpenClose', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/* , "trace" => $ex->getTraceAsString() */));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    function getRouteCatalogAction(){
        $params = $this->getRequest()->getPostJson();
        $routeName = $this->getArrayValue('param1', $params);

        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'listar');
            $conn = $this->getConnection();
            $parameters = array($this->userSessionId,$routeName);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_routeCatalog_list', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (PDOException $ex) {
            $errMsg = $ex->getMessage(); //utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            }
            return;
        } catch (Exception $generalEx) {
            echo json_encode(array("error" => $generalEx->getMessage(), "code" => $generalEx->getCode(), "trace" => $generalEx->getTraceAsString()));
            return;
        }
        echo json_encode($resultsets);
    }
}